package weaver.jobs.cyjt.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年11月20日 15:15
 */
public class KingdeeUtil extends BaseBean {

    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    private static final int CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private OkHttpClient client;
    // 定义常量
    private static final String RES_CODE_ZERO = "0";

    public KingdeeUtil() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }


    /**
     * 获取token
     *
     * @return
     */
    private String getToken() {
        String token = "";
        JSONObject returnJson = getTokenBaseInfo();
        String apiUrl = returnJson.getString("apiUrl");
        JSONObject paramJson = returnJson.getJSONObject("paramJson");
        paramJson.put("nonce", UUID.randomUUID().toString());
        paramJson.put("timestamp", DateUtil.getFullDate());
        try {
            RequestBody body = RequestBody.create(mediaType, paramJson.toJSONString());
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (response.isSuccessful()) {
                if (!result.isEmpty()) {
                    JSONObject resultJsonObj = JSONObject.parseObject(result);
                    String errorCode = resultJsonObj.getString("errorCode");
                    if (RES_CODE_ZERO.equals(errorCode)) {
                        token = resultJsonObj.getJSONObject("data").getString("access_token");
                    }
                }
            }
        } catch (Exception e) {
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        return token;
    }

    /**
     * get请求
     *
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpGetRequest(String apiUrl) {
        String accesstoken = getToken();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .get()
                    .addHeader("accesstoken", accesstoken)
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("datas", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpGetRequest>>>>>Exception e:", e);
        }

        resultJson.put("message", responseMsg);
        return resultJson;
    }

    /**
     * Post请求
     *
     * @param params
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpPostRequest(String apiUrl, String params) {
        String accesstoken = getToken();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("accesstoken", accesstoken)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("datas", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }


    private JSONObject getTokenBaseInfo() {
        RecordSet rs = new RecordSet();
        JSONObject returnJson = new JSONObject();
        JSONObject paramJson = new JSONObject();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='getToken'");
        rs.next();
        String mainid = Util.null2String(rs.getString("id"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        rs.executeQuery("select * from uf_jdbwpzb_dt1 where mainid=?", mainid);
        while (rs.next()) {
            String qqcsj = Util.null2String(rs.getString("qqcsj"));
            String qqcsz = Util.null2String(rs.getString("qqcsz"));
            paramJson.put(qqcsj, qqcsz);
        }
        returnJson.put("apiUrl", apiUrl);
        returnJson.put("paramJson", paramJson);
        return returnJson;
    }

    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param map
     */
    public int insertModelData(String tablename, Map<String, Object> map) {
        int dataid = 0;
        int userid = 1;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            rs.executeQuery("select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename='" + tablename + "'");
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values" +
                    "('" + uuid + "','" + userid + "','" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "','" + modeid + "')";
            if (rs.executeUpdate(insSql)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid='" + uuid + "'");
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        writeLog(">>>>>insertModelData>>>>updatesql=" + updatesql);
                        if (!rs.executeUpdate(updatesql)) {
                            rs1.executeUpdate("delete from " + tablename + " where id=?", dataid);
                            dataid = 0;
                        }
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }

    /**
     * 更新明细表单信息
     */
    public boolean insertDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>insertDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 删除明细表单信息
     */
    public boolean deleteDetailData(String tablename, int dataid) {
        RecordSet rs = new RecordSet();
        return rs.executeUpdate("delete from " + tablename + " where mainid=?",dataid);
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param map       数据集合
     * @param dataid    更新用唯一标识
     * @return
     */
    public int updateModelData(String tablename, String dataid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tablename + " where wyid=?", dataid);
        rs.next();
        int id = Util.getIntValue(rs.getString("id"), 0);
        if (id > 0) {
            String updatesql = "update " + tablename + " set  ";
            String valuesStr = "";
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                if (valuesStr.equals("")) {
                    valuesStr = key + "='" + map.get(key) + "'";
                } else {
                    valuesStr += "," + key + "='" + map.get(key) + "'";
                }
            }
            updatesql += valuesStr + " where wyid='" + dataid + "'";
            writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
            rs.executeUpdate(updatesql);
        }
        return id;
    }

    /**
     * 判断数据是否存在
     *
     * @param fileName
     * @param tableName
     * @return
     */
    public String isExistData(String fileName, String tableName) {
        StringBuilder sb = new StringBuilder();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select " + fileName + " from " + tableName);
        while (rs.next()) {
            String value = Util.null2String(rs.getString(1));
            sb.append(value).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * @Description: 判断是否是json数组格式
     */
    public boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * @Description: 判断是否是json格式
     */
    public boolean isJSONObject(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONObject.parseObject(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

}
